<template>
  <div class="search-result-container">
    <!-- 点击实现后退效果 -->
    <van-nav-bar
      title="搜索结果"
      left-arrow
      @click-left="$router.back()"
      fixed
    />
    <!-- 文章的ITEM项 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :immediate-check="false"
    >
      <ArtItem
        v-for="item in searchList"
        :key="item.art_id"
        :article="item"
        :closable="false"
      ></ArtItem>
    </van-list>
  </div>
</template>

<script>
import { SearchResultAPI } from '../../api/searchAPI'
import ArtItem from '../../components/ArtItem/ArtItem.vue'
export default {
  watch: {
    kw () {
      // 1. 重置关键数据
      this.page = 1
      this.artList = []
      this.loading = false
      this.finished = false

      // 2. 请求数据
      this.initSearchList()
    }
  },
  props: ['kw'],
  components: {
    ArtItem
  },
  created () {
    this.initSearchList()
  },
  activated () {
    window.addEventListener('scroll', this.scrollHandler())
  },
  deactivated () {
    window.removeEventListener('scroll', this.scrollHandler())
  },
  name: 'SearchResult',
  data () {
    return {
      // 页码值
      page: 1,
      // 文章的列表数据
      searchList: [],
      loading: false,
      finished: false
    }
  },
  methods: { // 初始化搜索结果
    async initSearchList () {
      // 调用API接口
      const { data: res } = await SearchResultAPI(this.kw, this.page)
      if (res.message === 'OK') {
        // .拼接数据 旧数据在前，新数据再后
        this.searchList = [...this.searchList, ...res.data.results]
        // 加载一页后将loading设置为false
        this.loading = false
        // 判断数据是否加载完毕
        if (res.data.results.length === 0) {
          this.finished = true
        }
        this.page += 1
      }
    },
    onLoad () {
      this.initSearchList()
    },

    // 处理滚动条滚动的事件处理函数
    // 把滚动的位置
    scrollHandler () {
      this.$route.meta.top = window.scrollY

      console.log(window.scrollY)
    }
  }
  // beforeRouteLeave (to, from, next) {
  //   from.meta.top = window.scrollY
  //   setTimeout(() => {
  //     next()
  //   }, 0)
  // }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>
